package com.cf.invoker.http.server;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import com.cf.invoker.HttpInvokerConstant;
import com.cf.invoker.InvokerServerProperty;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

/****
 *
 * @Author zhu-mingming
 * @Description
 * @Date 2018/10/23
 *
 **/

public class JettyInvokServer implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private InvokerServerProperty invokerServerProperty;

    @Autowired
    private ServiceRegisterStore serviceRegisterStore;

    private void start(int port) throws Exception {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.setBaseDir(".");
        tomcat.getHost().setAutoDeploy(false);

        String contextPath = "";
        StandardContext context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());
        tomcat.getHost().addChild(context);

        tomcat.addServlet(contextPath, "InvokHandlerServlet", new InvokHandlerServlet());
        context.addServletMappingDecoded(HttpInvokerConstant.ROOT_URL, "InvokHandlerServlet");
        tomcat.start();
        System.out.println("****** Tomcat server start in " + port + " ******");
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        if (serviceRegisterStore.getSize() <= 0) {
            return;
        }
        int port = invokerServerProperty.getPort();
        try {
            start(port);
        } catch (Exception e) {
            throw new BizException(EnumReturnCode.ERROR.getCode(), "###Http-Invoker###启动失败！", e);
        }
    }
}
